// index.js
// 获取应用实例

const app = getApp()

const version = "1.0.0"

const dithering = require('dithering.js')
const logs = require('../logs/log_func.js')

function writeFile(file_name, data) {
  // 获取文件系统管理器
  const fs = wx.getFileSystemManager();
  // 同步接口
  try {
    const res = fs.writeFileSync(
      `${wx.env.USER_DATA_PATH}/${file_name}`,
      data,
      'utf8'
    )
    console.log("write data:", file_name)
  } catch (e) {
    console.error(e)
    return e
  }
}

function readFile(file_name) {
  // 获取文件系统管理器
  const fs = wx.getFileSystemManager();
  try {
    const res = fs.readFileSync(`${wx.env.USER_DATA_PATH}/${file_name}`, 'utf8', 0)
    console.log('读取的文件内容：', res)

    return (res)
  } catch (e) {
    console.error(e)
  }

}

function ab2hex(buffer) {
  let hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}


Page({
  data: {
    buttons: [{
      text: '取消'
    }, {
      text: '确认'
    }],
    version: '',
    password: '',
    motto: 'Hello World2',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseGetUserProfile: false,
    canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName'), // 如需尝试获取用户信息可改为false
    devices: [],
    connecting: false,
    connected: false,
    readValue: "",
    chs: [],
    canWrite: false,
    logs: [],
    // log_list: [],
    newDate: "",
    _deviceId: "",
    _serviceId: "",
    _characteristicId: "",
    _characteristicdId_read: "",
    dataType: false,
    canvas: "",
    debug: [],
    chs: [],
    checknum: 0,
    my_step: 450,
    // my_ble_step: 240,
    canvas: "",
    epd_inti: false,
    weather_flag: false,
    sendjson: {},
    note_input: "",
    src: '',
    logo_default_src: '/pages/index/image/logo.png',
    logo_src: '',
    image_type: '',
    config: {
      epd: {
        model: "epd_EPD420Z96",
        width: 300,
        height: 400,
        color: 3,
        rotation: 1, //初始
        rotationSet: 0, //旋转
      },
      epd_image_width: 350, //300,
      page_image: {
        threshold_set: 50, //0-100
        epd_model_index: 4,
        rotate_index: 0,
        dithering_index: 0,
      },
      page_note: {
        date: "2023-09-01",
        today_flag: true,
        city: "深圳",
        logo: "X Z C R A Z Y",
      },
      page_setting: {
        qrcode: "",
        string1: "",
        string2: "",
        // string3:"",
        ble_name: "XZCRAZY's"
      },
      pen: {
        size: '10',
        color: 'black',
        back_color: "white",
      },
      page_custom_image: {
        mode_index: 0,
        mode_select: {},
      },
      page_select_value: 'page_select_image',
      ble_cmd_type: 'HEX', //JSON.HEX
      my_ble_step: 240,
      ble_send_interval: 1, //ms
      hid_send_interval: 1, //ms
      ble_send_interval_hid: 300, //ms
      hid_send_num: 2,
      platform: '',
      page_servo_setting: {
        rotate_degree: 30,
        lift_degree: 0,
        lift_delay: 1000, //ms
        degree_adjust: 0,
        page_rotate: 0,
      },
    },

    epd_model_select: {
      // array: ['1.54', '4.2c', '5.83c', '7.5c', '1.54c'],
      array: ['1.54', '2.66c', '2.66hc', '2.9c', '4.2c', '5.83c', '7.5c', '2.7'],
      objectArray: [{
        id: 0,
        name: '1.54',
        epd: {
          model: "epd_EPD154C1",
          width: 200,
          height: 200,
          color: 2,
          rotation: 0, //初始
          rotationSet: 0, //旋转
        },
      },
      {
        id: 1,
        name: '2.66c',
        epd: {
          model: "epd_EPD266Z90",
          width: 296,
          height: 152,
          color: 3,
          rotation: 1, //初始
          rotationSet: 0, //旋转
        },
      },
      {
        id: 2,
        name: '2.66hc',
        epd: {
          model: "epd_EPD266H850",
          width: 360,//296,
          height: 184,//152,
          color: 3,
          rotation: 1, //初始
          rotationSet: 0, //旋转
        },
      },
      {
        id: 3,
        name: '2.9c',
        epd: {
          model: "epd_EPD290Z94",
          width: 296,
          height: 128,
          color: 3,
          rotation: 1, //初始
          rotationSet: 0, //旋转
        },
      },
      {
        id: 4,
        name: '4.2c',
        epd: {
          model: "epd_EPD420Z96",
          width: 300,
          height: 400,
          color: 3,
          rotation: 1, //初始
          rotationSet: 0, //旋转
        },
      },
      {
        id: 5,
        name: '5.83c',
        epd: {
          model: "epd_EPD583Z83",
          width: 648,
          height: 480,
          color: 3,
          rotation: 0, //初始
          rotationSet: 0, //旋转
        },
      },
      {
        id: 6,
        name: '7.5c',
        epd: {
          model: "epd_EPD750A15",
          width: 800,
          height: 480,
          color: 3,
          rotation: 0, //初始
          rotationSet: 0, //旋转
        },
      },
      {
        id: 7,
        name: '2.7c',
        epd: {
          model: "epd_EPD270T91",
          width: 176,
          height: 264,
          color: 2,
          rotation: 0, //初始
          rotationSet: 0, //旋转
        },
      },
      ],
    },
    rotate_select: {
      array: ['0', '↻90', '180', '↺90'],
      objectArray: [{
        id: 0,
      },
      {
        id: 1,
      },
      {
        id: 2,
      },
      {
        id: 3,
      }
      ]
    },

    dithering_select: {
      array_2: ["色阶法", "bayer", "floydsteinberg", "Atkinson", "素描", "4阶灰度", "16阶灰度"],
      array_3: ["色阶法", "bayer", "floydsteinberg", "Atkinson", "素描", "(BWR)色阶法", "(BWR)floydsteinberg", "(BWR)Atkinson", "(BWR)8阶灰度"],
      objectArray: [{
        id: 0,
        value2: 'level',
        value3: 'level',
      },
      {
        id: 1,
        value2: 'bayer',
        value3: 'bayer',
      },
      {
        id: 2,
        value2: 'floydsteinberg',
        value3: 'floydsteinberg',
      },
      {
        id: 3,
        value2: 'Atkinson',
        value3: 'Atkinson',
      },
      {
        id: 4,
        value2: 'sketch',
        value3: 'sketch',
      },
      {
        id: 5,
        value2: 'grey_4bit',
        value3: 'bwr_level',
      },
      {
        id: 6,
        value2: 'grey_16bit',
        value3: 'bwr_floydsteinberg',
      },
      {
        id: 7,
        value2: '',
        value3: 'bwr_Atkinson',
      },
      // {
      //   id: 8,
      //   value2: '',
      //   value3: 'grey_bwr_4bit',
      // },
      {
        id: 8,
        value2: '',
        value3: 'grey_bwr_8bit',
      },
      ],
      dithering_index: 0,
    },
    threshold_select_display_flag: false,
    pen_size_display_display_flag: false,
    pen_color_display_display_flag: false,
    pen_back_color_display_display_flag: false,
    tuya_flag: false,
    startX: 0, //保存X坐标轴变量
    startY: 0, //保存X坐标轴变量
    isClear: false, //是否启用橡皮擦标记
    custom_image_mode0_data: {},
    epd_model: "",  
    epd_bat_percent: 0,
    current_Date: "",
    current_Time: "",
    input_text: "",
    input_text_length: 0,
    servo_rotate_degree: 0,
  },

  canvas_imagedata_list: {
    do: [],
    undo: []
  },

  toCropper: function (e) {
    console.log(e)
    console.log(e.currentTarget.dataset.param)
    let width
    let height
    let src
    // src = this.data.src
    if (e.currentTarget.dataset.param == 'image') {
      // width =  this.data.config.this.data.config.epd.width
      // height = this.data.config.epd.height
      width = this.data.config.epd_image_width
      height = this.data.config.epd_image_width / this.data.config.epd.width * this.data.config.epd.height
      src = this.data.src
    } else if (e.currentTarget.dataset.param == 'image_logo') {
      // width = 100
      // height = 100
      width = this.data.config.epd_image_width
      height = this.data.config.epd_image_width
      src = this.data.logo_src
    }
    this.setData({
      image_type: e.currentTarget.dataset.param
    })
    wx.navigateTo({
      url: '../cropper/cropper?imgSrc=' + src + '&width=' + width + '&height=' + height
    })
  },
  onShow() {

    if (app.globalData.imgSrc) {
      if (this.data.image_type == 'image')
        this.setData({
          src: app.globalData.imgSrc
        })
      else if (this.data.image_type == 'image_logo') {
        this.setData({
          logo_src: app.globalData.imgSrc
        })
        wx.setStorageSync('logo_src', this.data.logo_src)
        this.custom_image_display(false)
      }
    }

  },



  page_select: function (e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)
    this.setData({
      "config.page_select_value": e.detail.value
    })
    wx.setStorageSync('config', this.data.config)
  },

  modeXonImgOK(e) {
    console.log(e)
    this.setData({
      modexpath: e.detail.path
    })
    this.imageonload()
  },





  // 事件处理函数
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },

  bindPickerChange_epd_model: function (e) {
    console.log('picker(epd_model)发送选择改变，携带值为', e.detail.value)
    this.epd_model_select(e.detail.value)
    this.imageonload()
  },

  epd_model_select: function (value) {
    let str = 'config.page_image.epd_model_index'
    let str2 = 'config.epd'
    // console.log(value)
    this.setData({
      [str]: value,
      [str2]: this.data.epd_model_select.objectArray[value].epd,
    })
    wx.setStorageSync('config', this.data.config)
    app.globalData.epd_width = this.data.config.epd.width
    app.globalData.epd_height = this.data.config.epd.height

    let mode_select
    switch (this.data.epd_model_select.objectArray[this.data.config.page_image.epd_model_index].name) {
      case '1.54':
        mode_select = this.data.mode_select_154
        break;
      case '2.66c':
        mode_select = this.data.mode_select_266c
        break;
      case '2.66hc':
        mode_select = this.data.mode_select_266hc
        break;
      case '2.9c':
        mode_select = this.data.mode_select_290c
        break;
      case '4.2c':
        mode_select = this.data.mode_select_420c
        break;
      case '7.5c':
        mode_select = this.data.mode_select_750c
        break;
      case '5.83c':
        mode_select = this.data.mode_select_583c
        break;
      // case '1.54c':
      //   mode_select = this.data.mode_select_154
      //   break;
      default:
        break;
    }
    let str3 = 'config.page_custom_image.mode_select'
    let str4 = 'config.page_custom_image.mode_index'
    this.setData({
      [str3]: mode_select,
      [str4]: 0
    })



  },

  bindPickerChange_rotate: function (e) {
    console.log('picker(rotate)发送选择改变，携带值为', e.detail.value)
    this.epd_rotate_select(e.detail.value)
    this.imageonload()
  },

  epd_rotate_select: function (value) {

    let str = 'config.page_image.rotate_index'
    let str2 = 'config.epd'

    let epd_temp = JSON.parse(JSON.stringify(this.data.epd_model_select.objectArray[this.data.config.page_image.epd_model_index].epd))
    epd_temp.rotationSet = this.data.rotate_select.objectArray[value].id

    if ((value) & 1 == 1) {
      let height_temp = epd_temp.height;
      let width_temp = epd_temp.width;
      epd_temp.width = height_temp
      epd_temp.height = width_temp
    }

    this.setData({
      [str]: value,
      [str2]: epd_temp,
    })

    if (!this.data.src) {
      this.fill_canvas()
    }

    wx.setStorageSync('config', this.data.config)
    app.globalData.epd_width = this.data.config.epd.width
    app.globalData.epd_height = this.data.config.epd.height
  },


  bindPickerChange_dithering: function (e) {
    console.log('picker(dithering)发送选择改变，携带值为', e.detail.value)
    let id = e.detail.value

    this.epd_dithering_select(id)
    this.imageonload()
  },

  epd_dithering_select: function (value) {
    let str = 'config.page_image.dithering_index'
    this.setData({
      [str]: value,
    })
    wx.setStorageSync('config', this.data.config)
  },


  slider1change_threshold: function (e) {
    console.log('threshold发送选择改变，携带值为', e.detail.value)
    let str = 'config.page_image.threshold_set'

    this.setData({
      [str]: e.detail.value,
      threshold_select_display_flag: false,
    })
    this.imageonload()
  },


  imageonload() {
    console.log('图片加载')
    wx.showLoading({
      title: '加载中',
    })
    setTimeout(function () {
      wx.hideLoading()
    }, 200)

    this.canvas_imagedata_list = {
      do: [],
      undo: []
    }
    console.log(this.canvas_imagedata_list)

    if (this.data.config.page_select_value == 'page_select_image' || this.data.config.page_select_value == 'page_select_custom_image') {
      if (this.data.src || this.data.modexpath) {
        wx.createSelectorQuery()
          .select('#myCanvas')
          .fields({
            node: true,
            size: true
          })
          .exec(this.init.bind(this))

      }
    }
  },
  init(res) {
    console.log(res)
    // const width = res[0].width
    // const height = res[0].height
    const canvas = res[0].node
    this.setData({
      canvas
    })
    const ctx = canvas.getContext('2d')
    // console.log(dpr)
    // canvas.width = res[0].width // 获取宽
    // canvas.height = res[0].height // 获取高
    canvas.width = this.data.config.epd.width // 获取宽
    canvas.height = this.data.config.epd.height // 获取高
    // ctx.scale(dpr, dpr)
    console.log(canvas.width, canvas.height)

    const img = canvas.createImage()
    if (this.data.config.page_select_value == 'page_select_image') {
      img.src = this.data.src
    } else if (this.data.config.page_select_value == 'page_select_custom_image') {
      img.src = this.data.modexpath
    }
    img.onload = () => {

      ctx.fillStyle = 'white';
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

      var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height)

      var mode //test     
      mode = this.data.config.epd.color == 2 ? this.data.dithering_select.objectArray[this.data.config.page_image.dithering_index].value2 : this.data.dithering_select.objectArray[this.data.config.page_image.dithering_index].value3
      console.log(mode)

      imageData = dithering.convert_dithering(imageData, mode, this.data.config.page_image.threshold_set)

      console.log(imageData)

      ctx.putImageData(imageData, 0, 0)
    }
  },

  bindPickerChange_mode: function (e) {
    console.log('picker(mode)发送选择改变，携带值为', e.detail.value)
    let str = 'config.page_custom_image.mode_index'
    let mode_index = e.detail.value

    this.setData({
      [str]: mode_index,
    })
    wx.setStorageSync('config', this.data.config)

  },

  onLoad() {


    let platform
    let windowWidth
    wx.getSystemInfo({
      success(res) {
        console.log(res.model)
        console.log(res.pixelRatio)
        console.log(res.windowWidth)
        console.log(res.windowHeight)
        console.log(res.language)
        console.log(res.version)
        console.log(res.platform)
        platform = (res.platform)
        windowWidth = res.windowWidth
      }
    })

    console.log(this.data.config.epd_image_width)
    let password = wx.getStorageSync("password");
    this.setData({
      password
    })
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }

    wx.setStorageSync('logs', "")

    let config = wx.getStorageSync("config");

    console.log(config);
    if (config) {
      this.setData({
        config
      })
    } else {
      wx.setStorageSync('config', this.data.config)
    }
    if (1) {
      let str = 'config.epd_image_width'
      console.log(windowWidth * 0.9)
      this.setData({
        version,
        platform,
        [str]: windowWidth * 0.8,
      })
    }

    let logo_src = wx.getStorageSync("logo_src");

    console.log(logo_src);
    if (logo_src) {
      this.setData({
        logo_src
      })
    }
    app.globalData.epd_width = this.data.config.epd.width
    app.globalData.epd_height = this.data.config.epd.height


  },

  getUserProfile() {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },
  getUserInfo(e) {
    // 不推荐使用getUserInfo获取用户信息，预计自2021年4月13日起，getUserInfo将不再弹出弹窗，并直接返回匿名的用户个人信息
    console.log(e)
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },

  password_comfirm(e) {
    console.log(e.detail.value)
    let password = e.detail.value
    this.setData({
      password
    })
    wx.setStorageSync('password', password)
  },

  //在消息提示框中打印信息。其实这里是对shouToast的封装
  printInfo: function (info) {
    wx.showToast({
      title: info,
      icon: 'none',
      duration: 1200,
      mask: true
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    //模拟加载
    setTimeout(function () {
      // complete
      wx.hideNavigationBarLoading() //完成停止加载
      wx.stopPullDownRefresh() //停止下拉刷新
    }, 500)
    const pages = getCurrentPages();
    // console.log(pages)
    // const currPage = pages[pages.length - 1];//当前页面
    const url = '/' + pages[pages.length - 1].route; //当前页面
    // console.log(url)
    wx.redirectTo({
      url: url,
      success: function (res) {
        console.log('页面刷新成功');
      },
      fail: function (res) {
        console.log('页面刷新失败');
      }
    })
  },

  concatenate(...arrays) {
    let totalLen = 0;
    for (let arr of arrays)
      totalLen += arr.byteLength;
    let res = new Uint8Array(totalLen)
    let offset = 0
    for (let arr of arrays) {
      let uint8Arr = new Uint8Array(arr)
      res.set(uint8Arr, offset)
      offset += arr.byteLength
    }
    return res.buffer
  },

  bindClearLog() {
    this.setData({
      logs: [],
    })

  },


  /**
   * @brief 获取数据的校验和
   *
   * @return UINT8
   */
  checksum(oldArray) {
    let sum = 0;

    oldArray.forEach((item) => {
      sum += item;
    })
    sum &= 0xFF;
    return sum;
  },

  nfcstart() {
    logs.printLog("启动NFC...")
    // let dithering_select = this.data.dithering_select.objectArray[this.data.config.page_image.dithering_index].value
    let dithering_select = this.data.config.epd.color == 2 ? this.data.dithering_select.objectArray[this.data.config.page_image.dithering_index].value2 : this.data.dithering_select.objectArray[this.data.config.page_image.dithering_index].value3

    // if ((this.data.config.epd.model == 'epd_EPD154C1' & (!dithering_select.startsWith('bwr')) || this.data.config.epd.model == 'epd_EPD154Z90' || this.data.config.epd.model == 'epd_EPD290Z94' || this.data.config.epd.model == 'epd_EPD266Z90' || this.data.config.epd.model == 'epd_EPD420Z96' ||  this.data.config.epd.model == 'epd_EPD266H850')) {
    if (1) {
      wx.navigateTo({
        url: '../nfc/nfc'
      })

    } else {
      wx.showToast({
        title: 'NFC不支持！！！',
        icon: 'none',
      })
      logs.printLog("NFC不支持！！！")
    }
  },

  bind_threshold_select_tap: function (e) {
    // console.log(e)
    let flag = !this.data.threshold_select_display_flag
    this.setData({
      threshold_select_display_flag: flag,
    })
    wx.setStorageSync('config', this.data.config)
  },

  pen_Size_Select: function (e) { //更改画笔大小的方法
    console.log(e.currentTarget);
    let flag = !this.data.pen_size_select_display_flag
    this.setData({
      pen_size_select_display_flag: flag,
      isClear: false,
    })
    wx.setStorageSync('config', this.data.config)
    // this.isClear = false;
  },


  slider1change_pensize: function (e) {
    console.log('pen.size发送选择改变，携带值为', e.detail.value)
    let str = 'config.pen.size'

    this.setData({
      [str]: e.detail.value,
      pen_size_select_display_flag: false,
    })
    wx.setStorageSync('config', this.data.config)
  },

  color_Select: function (e) { //更改画笔大小的方法
    console.log(e.currentTarget);
    let a = e.currentTarget.dataset.param + '_select_display_flag'
    let flag
    let other_flag
    if (e.currentTarget.dataset.param === 'pen_color') {
      flag = !this.data.pen_color_select_display_flag
      other_flag = 'pen_back_color_select_display_flag'
    } else if (e.currentTarget.dataset.param === 'pen_back_color') {
      flag = !this.data.pen_back_color_select_display_flag
      other_flag = 'pen_color_select_display_flag'
    }
    this.setData({
      [a]: flag,
      [other_flag]: false,
      isClear: false,
    })

    wx.setStorageSync('config', this.data.config)
  },


  color_Select_List: function (e) { //更改画笔大小的方法
    console.log(e);
    // console.log(e.target.id);
    let color = e.target.id.substring(6) //color-
    console.log(color);
    if (color) {
      let str, str2
      if (this.data.pen_color_select_display_flag) {
        str = "config.pen.color"
        str2 = "pen_color_select_display_flag"
      } else if (this.data.pen_back_color_select_display_flag) {
        str = "config.pen.back_color"
        str2 = "pen_back_color_select_display_flag"

        if (!this.data.src) {
          this.fill_canvas()
        }
      }

      this.setData({
        [str]: color,
        [str2]: false,
        isClear: false,
      })
      wx.setStorageSync('config', this.data.config)

    }
  },


  fill_canvas() {
    wx.createSelectorQuery()
      .select('#myCanvas')
      .fields({
        node: true,
        size: true
      })
      .exec(this.init_canvas.bind(this))
  },



  init_canvas(res) {
    console.log(res)
    // const width = res[0].width
    // const height = res[0].height
    const canvas = res[0].node
    this.setData({
      canvas,
      tuya_flag: true,
    })
    const ctx = canvas.getContext('2d')
    canvas.width = this.data.config.epd.width // 获取宽
    canvas.height = this.data.config.epd.height // 获取高
    // ctx.scale(dpr, dpr)
    console.log(canvas.width, canvas.height)
    ctx.fillStyle = this.data.config.pen.back_color;
    ctx.fillRect(0, 0, canvas.width, canvas.height);

  },

  clear_canvas(e) {
    const canvas = this.data.canvas;
    if (canvas) {
      const ctx = canvas.getContext('2d')

      ctx.clearRect(0, 0, canvas.width, canvas.height);
      if (this.data.tuya_flag) {
        this.setData({
          // src: '',
          tuya_flag: false,
          // canvas:undefined,
          isClear: false,
        })
        if (this.data.src || this.data.modexpath) {
          this.imageonload()
        }
      } else {
        if (e.currentTarget.dataset.param == 'image') {
          this.setData({
            src: '',
          })
        } else if (e.currentTarget.dataset.param == 'image_logo') {
          this.setData({
            logo_src: '',
          })
          wx.setStorageSync('logo_src', '')
        }
        this.setData({
          canvas: undefined,
          isClear: false,
        })

      }
      // console.log(this.data.src,this.data.tuya_flag)
    }
  },

  //手指触摸动作开始
  touchStart: function (e) {
    //得到触摸点的坐标
    const canvas = this.data.canvas;
    if (canvas) {
      console.log(e)

      let canvas_scale = this.data.config.epd_image_width / this.data.config.epd.width
      this.data.startX = e.changedTouches[0].x / canvas_scale
      this.data.startY = e.changedTouches[0].y / canvas_scale
      const context = canvas.getContext('2d')

      console.log(this.canvas_imagedata_list.do.length)
      console.log(this.canvas_imagedata_list.do)

      const image = context.getImageData(0, 0, canvas.width, canvas.height)
      this.canvas_imagedata_list.do.push(image)
      this.canvas_imagedata_list.undo = []
      console.log(this.canvas_imagedata_list)

      if (this.data.isClear) { //判断是否启用的橡皮擦功能  ture表示清除  false表示画画
        context.strokeStyle = this.data.config.pen.back_color //设置线条样式 此处设置为画布的背景颜色  橡皮擦原理就是：利用擦过的地方被填充为画布的背景颜色一致 从而达到橡皮擦的效果 
        context.lineCap = ('round') //设置线条端点的样式
        context.lineJoin = ('round') //设置两线相交处的样式
        //  context.lineWidth=(20) //设置线条宽度
        context.lineWidth = (this.data.config.pen.size * 2)
        context.save(); //保存当前坐标轴的缩放、旋转、平移信息
        context.beginPath() //开始一个路径 
        context.arc(this.data.startX, this.data.startY, 5, 0, 2 * Math.PI, true); //添加一个弧形路径到当前路径，顺时针绘制  这里总共画了360度  也就是一个圆形 
        context.fill(); //对当前路径进行填充
        context.restore(); //恢复之前保存过的坐标轴的缩放、旋转、平移信息
      } else {
        context.strokeStyle = this.data.config.pen.color
        context.lineWidth = (this.data.config.pen.size)
        context.lineCap = ('round') // 让线条圆润 
        context.beginPath()

      }
      this.setData({
        tuya_flag: true,
      })
    }
  },
  //手指触摸后移动
  touchMove: function (e) {

    const canvas = this.data.canvas;
    if (canvas) {
      const context = canvas.getContext('2d')
      // var startX1 = e.changedTouches[0].x
      // var startY1 = e.changedTouches[0].y
      let canvas_scale = this.data.config.epd_image_width / this.data.config.epd.width
      var startX1 = e.changedTouches[0].x / canvas_scale
      var startY1 = e.changedTouches[0].y / canvas_scale
      if (this.data.isClear) { //判断是否启用的橡皮擦功能  ture表示清除  false表示画画

        context.save(); //保存当前坐标轴的缩放、旋转、平移信息
        context.moveTo(this.data.startX, this.data.startY); //把路径移动到画布中的指定点，但不创建线条
        context.lineTo(startX1, startY1); //添加一个新点，然后在画布中创建从该点到最后指定点的线条
        context.stroke(); //对当前路径进行描边
        context.restore() //恢复之前保存过的坐标轴的缩放、旋转、平移信息

        this.data.startX = startX1;
        this.data.startY = startY1;

      } else {
        context.moveTo(this.data.startX, this.data.startY)
        context.lineTo(startX1, startY1)
        context.stroke()

        this.data.startX = startX1;
        this.data.startY = startY1;

      }

      context.stroke()
    }
  },

  //手指触摸动作结束
  touchEnd: function () {
    // this.test()
    const canvas = this.data.canvas;
    if (canvas) {
      const context = canvas.getContext('2d')
      context.save() //存储
      context.restore(); //弹出存储状态
      const image = context.getImageData(0, 0, canvas.width, canvas.height)
      this.canvas_imagedata_list.undo.push(image)
      console.log(this.canvas_imagedata_list)
    }
  },


  undo: function () {
    // this.test()
    const canvas = this.data.canvas;
    if (canvas) {
      const context = canvas.getContext('2d')

      if (this.canvas_imagedata_list.do.length > 0) {
        const image = this.canvas_imagedata_list.do.pop()
        this.canvas_imagedata_list.undo.push(image)
        console.log(this.canvas_imagedata_list)
        context.putImageData(image, 0, 0)
      }
    }
  },


  redo: function () {
    // this.test()
    const canvas = this.data.canvas;
    if (canvas) {
      const context = canvas.getContext('2d')
      if (this.canvas_imagedata_list.undo.length > 1) {
        const image = this.canvas_imagedata_list.undo.pop()
        this.canvas_imagedata_list.do.push(image)
        console.log(this.canvas_imagedata_list)
        const image2 = this.canvas_imagedata_list.undo[this.canvas_imagedata_list.undo.length - 1]
        context.putImageData(image2, 0, 0)
      }
    }
  },

  //启动橡皮擦方法
  eraser_select: function () {
    this.setData({
      isClear: !this.data.isClear
    })
  },

  clear_all() {
    wx.clearStorageSync()
  },

  ble_cmd_type_swtich() {
    this.setData({
      ['config.ble_cmd_type']: this.data.config.ble_cmd_type == "JSON" ? "HEX" : "JSON"
    })
    wx.setStorageSync('config', this.data.config)

  },

  custom_image_mode0_draw() {
    wx.showLoading()
    const that = this
    const query = wx.createSelectorQuery().in(this);
    query.select('#my-canvas').fields({ // 选择需要生成canvas的范围
      size: true,
      scrollOffset: true
    }, data => {
      let width = this.data.config.epd.width;
      let height = this.data.config.epd.height;
      that.setData({
        width,
        height
      })
      setTimeout(() => {
        that.startDraw()
      }, 500);
    }).exec()
  },
  startDraw() {
    let that = this

    // 创建wxml2canvas对象
    let drawMyImage = new Wxml2Canvas({
      element: 'myCanvas', // canvas的id,
      obj: that, // 传入当前组件的this
      width: that.data.width * 1,
      height: that.data.height * 1,
      background: '#FFFFFF', // 生成图片的背景色
      progress(percent) { // 进度
        // console.log(percent);
      },
      finish(url) { // 生成的图片
        wx.hideLoading()
        //             that.savePoster(url)
      },
      error(res) { // 失败原因
        console.log(res);
        wx.hideLoading()
      }
    }, this);
    let data = {
      // 获取wxml数据
      list: [{
        type: 'wxml',
        class: '.my_canvas .my_draw_canvas', // my_canvas要绘制的wxml元素根类名， my_draw_canvas单个元素的类名（所有要绘制的单个元素都要添加该类名）
        limit: '.my_canvas', // 要绘制的wxml元素根类名
        x: 0,
        y: 0
      }]
    }
    // 绘制canvas
    drawMyImage.draw(data, this);
  },
  savePoster() {
    const that = this
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imgUrl,
      success: function () {
        wx.showToast({
          title: '保存成功',
          icon: 'none',
          duration: 1500
        });
      },
      fail(err) {
        if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail authorize no response") {
          wx.showModal({
            title: '提示',
            content: '需要您授权保存相册',
            showCancel: false,
            success: modalSuccess => {
              wx.openSetting({
                success(settingdata) {
                  if (settingdata.authSetting['scope.writePhotosAlbum']) {
                    wx.saveImageToPhotosAlbum({
                      filePath: that.data.imgUrl,
                      success: function () {
                        wx.showToast({
                          title: '保存成功',
                          icon: 'success',
                          duration: 2000
                        })
                      },
                    })
                  } else {
                    wx.showToast({
                      title: '授权失败，请稍后重新获取',
                      icon: 'none',
                      duration: 1500
                    });
                  }
                }
              })
            }
          })
        }
      }
    })
  },


})